import { useState, useEffect } from "react";
import { Form, Input, Row, Col, Card, message, Switch, Alert } from "antd";
import { CommonModal } from "@/views/components/CommonModal";
import styles from "./index.module.less";
import Iconfont from "@/components/IconFont";
import CryptoJS from "crypto-js";
import { makeinventoryPay, batchPrintByExpressSuccessNotify, cashpaymentMethod, updatePrint } from "../service";
import CommonInput from "@/pages/OrderModule/common/components/CommonInput";
import { usePrintExpress } from "@/views/hooks/usePrintExpress";
import { usePrintUniqueCode } from "@/views/hooks/usePrintUniqueCode";
import { printKmUniqcode } from '@/utils/printKm.js';

//去支付
const goPay = ({ data, fetchList, selectedRows, handleOk, handleCancel, printExpressList, addVisible, priceSum, dataSource }) => {
	const [form] = Form.useForm();
	const [method, setMethod] = useState(1);
	const [payData, setPayData] = useState([]);
	const [printSetVisible, setPrintSetVisible] = useState(false);
	const [isDeduction, setIsDeduction] = useState(false);
	const printUpdateRequest = updatePrint;

	const { printExpress } = usePrintExpress({
		callback: data => {
			if (data.modalOK) {
				onCancel();
				return;
			}
			console.log(data, "sssssssssaaaa");
			// 执行修改打印状态接口
			if (data.successList) {
				console.log(data.successList, data.successList);
				batchPrintByExpressSuccessNotify([...data.successList.map(e => e.logisticsNo)]).then(res => {
					const { success } = res;
					if (success) {
						fetchList();
						onCancel();
					}
				});
			}
		}
	}); //打印面单

	//打印唯一码
	const printUniqueCode = async (printList) => {
		const res = await getKuaiMaiPrint({
			codes: printList.map(v => v.code),
			labelType: 1
		})
		if (res.success) {
			const printerConfigs = getExpressRelativePrinter();
			console.log(res.data, printerConfigs, 'data')
			const printer = printerConfigs["唯一码"];
			if (!printer) {
				return message.info("唯一码打印请选择打印机");
			}
			printKmUniqcode(JSON.parse(res.data), printer, () => {
				savePrintRecord(printList);
			});
		}
	}


	const { initPrint, template, printData, printAction, getExpressRelativePrinter, setUniqueCodeRelativePrinter } =
		usePrintUniqueCode({
			callback: data => {
				if (data.printData) {
					onCancel();
					fetchList();
				}
			}
		}); //打印唯一码
	useEffect(() => {
		console.log(data, "data");
		form.setFieldValue("isDeduction", data.isDeductionOpen);
		setIsDeduction(data.isDeduction);
	}, [addVisible]);

	useEffect(() => { }, [selectedRows]);

	useEffect(() => {
		if (template.length !== 0) {
			if (template.panels.length > 0) {
				console.log(getExpressRelativePrinter()["唯一码"]);
				printAction([template, printData, getExpressRelativePrinter()["唯一码"]]);
			}
		}
	}, [template]);

	const makeinventoryMethodData = async () => {
		let param = {
			takeGoodList: selectedRows,
			isDeduction: isDeduction ? 1 : null,
			payType: method == 1 ? 0 : 1
		};
		const { data, success } = await cashpaymentMethod(param);
		if (success) {
			setPayData(data);
		}
	};
	useEffect(() => {
		console.log(payData, "payData");
	}, [payData]);
	const CheckRrintProps = {
		fetchList,
		selectedRows,
		handleOk() { },
		handleCancel() {
			setPrintSetVisible(0);
		}
	};
	useEffect(() => {
		makeinventoryMethodData();
	}, [method]);
	const makeinventoryPayFn = async () => {
		form.validateFields().then(async value => {
			console.log(value, "value");
			const { data, success } = await makeinventoryPay({
				payPassword: CryptoJS.MD5(value.payPwd).toString(),
				takeGoodList: selectedRows,
				isDeduction: payData.isDeduction,
				payType: method == 1 ? 0 : 1
			});
			if (success) {
				console.log(data, "data");
				handleCancel(data);
				// message.success("操作成功");
				// const areAllOutboundOrderNoListsEmpty = data.every(item => {
				// 	return item.outboundOrderNoList.length === 0;
				// });
				// const areCodeListEmpty = data.every(item => {
				// 	return item.codeList.length === 0;
				// });
				// if (areCodeListEmpty && areAllOutboundOrderNoListsEmpty) {
				// 	fetchList();
				// 	onCancel();
				// }
				// if (!areAllOutboundOrderNoListsEmpty) {
				// 	const printList = data.flatMap(item => item.outboundOrderNoList);
				// 	printExpress(printList);
				// 	// onCancel();
				// 	fetchList();
				// }
				// if (!areCodeListEmpty) {
				// 	const printList = data.flatMap(item => item.codeList);
				// 	for (let i = 0; i < printList.length; i++) {
				// 		printList[i].nums = i + 1;
				// 	}
				// 	const d = printList.map(e => {
				// 		return {
				// 			uniqueCode: e.code, //"条形码",
				// 			codeSN: e.nums, // "序号",
				// 			orderGoodsCount: e.skuQuantity, //"订单商品数量",
				// 			orderGoodsName: e.skuName, // "订单商品名称",
				// 			orderGoodsSpec: e.skuSpec, //"订单规格属性",
				// 			salesOrderSn: e.outboundNo // "销售出库单号"
				// 		};
				// 	});
				// 	initPrint(d);
				// }
			}
		});
	};

	const onOk = () => {
		// makeinventoryPayFn();
		form.validateFields().then(async value => {
			console.log(value, "value");
			const { data, success } = await makeinventoryPay({
				payPassword: CryptoJS.MD5(value.payPwd).toString(),
				takeGoodList: selectedRows,
				isDeduction: payData.isDeduction,
				payType: method == 1 ? 0 : 1
			});
			if (success) {
				console.log(data, "data");
				fetchList();
				onCancel();
				handleOk(data);
				message.success("操作成功");
			}
		});
	};
	const onChange = async e => {
		setIsDeduction(e);
		let param = {
			takeGoodList: selectedRows,
			isDeduction: e ? 1 : 0,
			payType: method == 1 ? 0 : 1
		};
		const { data, success } = await cashpaymentMethod(param);
		if (success) {
			setPayData(data);
		}
	};

	const onCancel = () => {
		handleCancel();
		form.resetFields();
	};
	return (
		<CommonModal title={{ title: "收银台" }} visible={addVisible} onOk={onOk} width={"464px"} onCancel={onCancel}>
			<Form form={form} name="stock-set-remark-modal">
				<div style={{ marginBottom: "12px" }}>
					<Row style={{ margin: "12px 20px 10px 16px" }}>
						<Col span={24}>
							<div className="flex" style={{ justifyContent: "space-between" }}>
								<div>应付总金额：</div>
								<span className={styles.co2641}>￥{payData.meetTotalAmount}</span>
							</div>
						</Col>
					</Row>
					<div style={{ display: "flex" }}>
						<div>
							<Card
								className={styles.cardStyle}
								style={{ border: method == "1" ? "1px solid rgba(0, 104, 255, 1)" : "" }}
								onClick={() => setMethod(1)}
							>
								<span className={styles.absolutedCenter}>
									<Iconfont type="iconyuezhifu-copy" style={{ fontSize: 40, marginRight: 10, color: "red" }}></Iconfont>
									<div>
										<span className="common-color11" style={{ fontSize: "14px", lineHeight: "14px" }}>
											余额支付
										</span>
										<div style={{ fontSize: "10px", lineHeight: "10px", color: "rgba(255, 67, 84, 1)" }}>免手续费</div>
									</div>
								</span>

								{method == "1" && <Iconfont className={styles.checkedBox} type="icontriangle" />}
							</Card>
						</div>
						{data.isAliOpen === 1 && (
							<Card
								className={styles.cardStyle}
								style={{ border: method == "2" ? "1px solid rgba(0, 104, 255, 1)" : "" }}
								onClick={() => setMethod(2)}
							>
								<span className={styles.absolutedCenter}>
									<Iconfont type="iconzhifupingtai-zhifubao-copy" style={{ fontSize: 40, marginRight: 10 }}></Iconfont>
									<div>
										<span className="common-color11" style={{ fontSize: "14px", lineHeight: "14px" }}>
											支付宝
										</span>
									</div>
								</span>
								{method == "2" && <Iconfont className={styles.checkedBox} type="icontriangle" />}
							</Card>
						)}
					</div>
				</div>
				{payData?.isDeductionOpen == 1 && (
					<Row style={{ margin: "0 20px 0 16px" }}>
						<Col span={24}>
							<div className="flex" style={{ justifyContent: "space-between" }}>
								{payData.isDeduction === 1 && (
									<Form.Item label="使用抵扣:" name="isDeduction">
										<Switch size="default" defaultChecked={true} onChange={onChange} />
									</Form.Item>
								)}
								{payData.isDeduction === 0 && (
									<Form.Item label="使用抵扣:" name="isDeduction">
										<Switch size="default" defaultChecked={false} onChange={onChange} />
									</Form.Item>
								)}
								<span className={styles.co2641}>￥{payData.deductionTotalAmount}</span>
							</div>
						</Col>
					</Row>
				)}
				{method == "1" && (
					<Row style={{ margin: "0 20px 10px 16px" }}>
						<Col span={24} className="mb20">
							<div className="flex" style={{ justifyContent: "space-between" }}>
								<div>账期应付：</div>
								<span className={styles.co2641}>￥{payData.creditTotalAmount}</span>
							</div>
						</Col>
						<Col span={24}>
							<div className="flex" style={{ justifyContent: "space-between" }}>
								<div>余额应付:</div>
								<span className={styles.co2641}>￥{payData.balanceTotalAmount}</span>
							</div>
						</Col>
					</Row>
				)}
				{method == "2" && (
					<Row style={{ margin: "0 20px 0 16px" }}>
						<Col span={24}>
							<div className="flex" style={{ justifyContent: "space-between" }}>
								<div>支付宝应付：</div>
								<span className={styles.co2641}>￥{payData.aliTotalAmount}</span>
							</div>
						</Col>
					</Row>
				)}

				<Row style={{ margin: "20px 0 0 16px" }}>
					<Col span={24}>
						<Form.Item name="payPwd" rules={[{ required: true, message: "请输入支付密码" }]}>
							<CommonInput Component={Input} placeholder="请输入支付密码" aria-required />
						</Form.Item>
					</Col>
				</Row>
				{method == "2" && (
					<Alert
						description="1.选择支付宝付款后，当前只是金额预览，还未发生实际支付，等到真正“拿货”后才会从支付宝扣款。2.请您确保支付宝余额充足及状态正常，以免影响订单正常流转。"
						type="warning"
						showIcon
						closable
					/>
				)}
			</Form>
			{printSetVisible && <ExpressPrintModal {...CheckRrintProps}></ExpressPrintModal>}
		</CommonModal>
	);
};

export default goPay;
